package com.keepsport.keepsportapi.serve;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.websocket.*;

import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/***
 *      ┌─┐       ┌─┐ + +
 *   ┌──┘ ┴───────┘ ┴──┐++
 *   │                 │
 *   │       ───       │++ + + +
 *   ███████───███████ │+
 *   │                 │+  
 *   │       ─┴─       │
 *   │                 │
 *   └───┐         ┌───┘
 *       │         │ 
 *       │         │   + +神兽保佑
 *       │         │      代码无BUG!
 *       │         └──────────────┐
 *       │                        │
 *       │                        ├─┐
 *       │                        ┌─┘
 *       │                        │
 *       └─┐  ┐  ┌───────┬──┐  ┌──┘  + + + +
 *         │ ─┤ ─┤       │ ─┤ ─┤
 *         └──┴──┘       └──┴──┘  + + + +
 *          Data:2022/7/5
 *          @author wyb
 *          Description
 */
@Component //IOC创建对象
@Scope(scopeName = "prototype") //设置IOC创建对象的方式 多例
@ServerEndpoint("/server/chat/{nickname}")
public class WebSocketServer {
    //记录当前在线的所有用户  key:用户昵称  value:会话对象
    public static ConcurrentHashMap<String,Session> map = new ConcurrentHashMap<>();
    private String name;
    //创建连接
    @OnOpen
    public  void opne(Session session, @PathParam("nickname") String name){
        if (map.containsKey(name)){
            try {
                session.getBasicRemote().sendText("昵称重复");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            //添加在线用户
            map.put(name,session);
            this.name = name;
            sendMoreMsg("欢迎"+name+"加入聊天室");
        }
    }
    //接受信息
    @OnMessage
    public void receive(String msg){
        sendMoreMsg(name+":"+msg);
    }
    //出现错误
    @OnError
    public void error(Session session,Throwable throwable){
        System.err.println("错误："+throwable.getMessage());
    }
    //断开连接
    @OnClose
    public void close(){
        map.remove(name);
        sendMoreMsg(name+"退出房间！");
        System.err.println("关闭");
    }
    public static void sendMoreMsg(String msg){
        //接收消息 转发消息
        for(String b:map.keySet()){
            try {
                map.get(b).getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
